package com.neusoft.myutils;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyUtil {
	/**
	 * log4j日志对象
	 */
	public static Log logRootLogger = LogFactory.getLog("rootLogger");
	
	/**
	 * 通过泛型和反射机制获取实例对象
	 * @param clazz
	 * 			class文件
	 * @return 实例对象
	 */
	public static <T> T getInstance(Class<T> clazz) {
		T tClazz = null;
		try {
			tClazz = clazz.newInstance();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return tClazz;
	}
	public static Integer coverStr2Integer(String str) {
		Integer val = null;
		try {
			val = Integer.parseInt(str);
		} catch (Exception e) {
			MyUtil.logRootLogger.info("数据类型转换异常："+e.getMessage());
		}
		
		return val;
	}
	/**
	 * 将request中的from表单的值设置给对应的实体bean对象
	 * @param req request对象
	 * @param clazzB 被设置的实体bean
	 * @return 实体bean
	 */
	public static <T> T convertRequestParameterToBean(HttpServletRequest req,Class<T> clazzB) {
		
		T bean = null;
		try {
			//创建bean的实例对象
			bean = clazzB.newInstance();
			//获取所有表单字段的name属性值
			Enumeration<String> paraNames = req.getParameterNames();
			//遍历每一个表单控件的name属性值
			String pName;
			String pValue;
			while(paraNames.hasMoreElements()) {
				//取出当前的name属性值
				pName = paraNames.nextElement();
				//取出name属性对应控件的value值
				pValue = req.getParameter(pName);
				//约定表单控件的name属性值和实体bean的属性字段名一一对应
				//利用beanutils工具类的setProperty方法将指定名字的值设置到实体bean上
				BeanUtils.setProperty(bean, pName, pValue);
			}
		} catch (Exception e) {
			// request参数转换为实体bean异常
			MyUtil.logRootLogger.info("数据类型转换异常："+e.getMessage());
		} 
		
		return bean;
		
	}
}
